package com.sx.micowell.module.smartDevice;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.example.mvvm.bar.TitleBar;
import com.example.mvvm.base.ContainerActivity;
import com.example.mvvm.base.action.TitleBarAction;
import com.example.mvvm.base.data.DataBindingConfig;
import com.example.mvvm.until.LogUtils;
import com.example.mvvm.until.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.sx.micowell.BR;
import com.sx.micowell.R;
import com.sx.micowell.databinding.FragDeviceListBinding;
import com.sx.micowell.framework.app.IntentKey;
import com.sx.micowell.framework.app.MyFragment;
import com.sx.micowell.framework.arouth.RouteManager;
import com.sx.micowell.framework.arouth.RoutePath;
import com.sx.micowell.framework.model.smartDevice.SmartDeviceListModel;
import com.sx.micowell.framework.tools.AppDialogUtils;
import com.sx.micowell.module.smartDevice.adapter.DeviceBoundListAdapter;
import com.tuya.smart.android.ble.builder.BleConnectBuilder;
import com.tuya.smart.android.blemesh.api.ITuyaBlueMeshDevice;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.home.sdk.bean.HomeBean;
import com.tuya.smart.sdk.api.IDevListener;
import com.tuya.smart.sdk.api.IResultCallback;
import com.tuya.smart.sdk.api.bluemesh.IMeshDevListener;
import com.tuya.smart.sdk.bean.DeviceBean;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: YY
 * @Time: 2021/9/16
 * @Describe 智能设备 - 列表
 */
@Route(path = RoutePath.SMART_DEVICE_LIST)
public class SmartDeviceBoundListFragment extends MyFragment<FragDeviceListBinding, ContainerActivity>
        implements TitleBarAction {

    private SmartDeviceListModel viewModel;

    private DeviceBoundListAdapter deviceListAdapter;


    IDevListener iDevListener = new IDevListener() {

        @Override
        public void onDpUpdate(String devId, String dpStr) {
            LogUtils.d("onDpUpdate");
        }

        @Override
        public void onRemoved(String devId) {
            LogUtils.d("onRemoved");
        }

        @Override
        public void onStatusChanged(String devId, boolean online) {
            LogUtils.d("onStatusChanged");
            if (deviceListAdapter != null) {
                if (deviceListAdapter.getData().size() > 0) {
                    for (DeviceBean item : deviceListAdapter.getData()) {
                        if (item.getIsOnline() != online) {
                            item.setIsOnline(online);
                            deviceListAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        }

        @Override
        public void onNetworkStatusChanged(String devId, boolean status) {
            LogUtils.d("onNetworkStatusChanged");
        }

        @Override
        public void onDevInfoUpdate(String devId) {
            LogUtils.d("onDevInfoUpdate");
        }
    };

    IMeshDevListener iMeshDevListener = new IMeshDevListener() {

        @Override
        public void onDpUpdate(String nodeId, String dps, boolean isFromLocal) {
            LogUtils.d("iMeshDevListener onDpUpdate");
        }

        @Override
        public void onStatusChanged(List<String> online, List<String> offline, String gwId) {
            LogUtils.d("iMeshDevListener onStatusChanged");
            if (deviceListAdapter != null) {
                deviceListAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onNetworkStatusChanged(String devId, boolean status) {
            LogUtils.d("iMeshDevListener onNetworkStatusChanged");
        }

        @Override
        public void onRawDataUpdate(byte[] bytes) {
            LogUtils.d("iMeshDevListener onRawDataUpdate");
        }

        @Override
        public void onDevInfoUpdate(String devId) {
            LogUtils.d("iMeshDevListener onDevInfoUpdate");
        }

        @Override
        public void onRemoved(String devId) {
            LogUtils.d("iMeshDevListener onRemoved");
        }
    };

    @Override
    protected void initViewModel() {
        super.initViewModel();
        viewModel = getFragmentScopeViewModel(SmartDeviceListModel.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.frag_device_list, BR.viewModel, viewModel);
    }

    @Override
    protected void initView() {
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true)
                .fitsSystemWindows(true).init();
        getBinding().title.setOnTitleBarListener(this);

        getBinding().layoutEmpty.tvAddDevice.setOnClickListener(v -> startContainerActivity(
                RouteManager.Companion.getInstance().getSelectAddDeviceFragment()
                        .getClass().getCanonicalName(),
                null));
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initViewObservable() {
        super.initViewObservable();

        setDeviceList();

        viewModel.homeBeanEvent.observe(this, homeBean -> {
            if (homeBean.getSigMeshList() != null && homeBean.getSigMeshList().size() > 0) {
                ITuyaBlueMeshDevice mTuyaSigMeshDevice = TuyaHomeSdk.newSigMeshDeviceInstance(homeBean.getSigMeshList().get(0).getMeshId());
                mTuyaSigMeshDevice.registerMeshDevListener(iMeshDevListener);
                TuyaHomeSdk.getTuyaSigMeshClient().startClient(TuyaHomeSdk.getSigMeshInstance().getSigMeshList().get(0));
            }
        });
    }

    @Nullable
    @Override
    public TitleBar getTitleBar() {
        return getBinding().title;
    }

    @Override
    public void onLeftClick(View v) {
        getMyActivity().finish();
    }

    @Override
    public void onRightClick(View v) {
        startContainerActivity(
                RouteManager.Companion.getInstance().getSelectAddDeviceFragment()
                        .getClass().getCanonicalName(),
                null);
    }

    public void setDeviceList() {
        getBinding().recyclerDevice.setNestedScrollingEnabled(false);
        getBinding().recyclerDevice.setLayoutManager(new LinearLayoutManager(getContext()));

        viewModel.deviceListData.observe(this, deviceBeans -> {
            if (deviceBeans != null && deviceBeans.size() > 0) {
                getBinding().layoutEmpty.line1.setVisibility(View.GONE);
                if (deviceListAdapter == null) {
                    deviceListAdapter = new DeviceBoundListAdapter(deviceBeans);
                    getBinding().recyclerDevice.setAdapter(deviceListAdapter);
                }

                deviceListAdapter.setOnItemClickListener((adapter, view, position) -> {
                    boolean isOnline = deviceBeans.get(position).getIsOnline();
                    String name = deviceBeans.get(position).getName();
                    String devId = deviceBeans.get(position).getDevId();

                    if (isOnline) {
                        Bundle bundle = new Bundle();
                        bundle.putString(IntentKey.DATA, name);
                        bundle.putString(IntentKey.ID, devId);
                        startContainerActivity(
                                RouteManager.Companion.getInstance().getDeviceDataFragment(name, devId)
                                        .getClass().getCanonicalName(),
                                bundle);
                    } else {
                        List<BleConnectBuilder> builderList = new ArrayList<>();
                        for (DeviceBean deviceBean : deviceBeans) {
                            TuyaHomeSdk.newDeviceInstance(deviceBean.devId).registerDevListener(iDevListener);
                            if (deviceBean.isBluetooth()) {
                                BleConnectBuilder builder = new BleConnectBuilder();
                                builder.setDevId(deviceBean.devId);
                                builderList.add(builder);
                            }
                        }
                        if (builderList.size() > 0) {
                            TuyaHomeSdk.getBleManager().connectBleDevice(builderList);
                        }
                    }
                });

                deviceListAdapter.setOnItemLongClickListener((adapter, view, position) -> {
                    String deviceId = deviceBeans.get(position).getDevId();
                    AppDialogUtils.showBasicDialog(getContext(),
                       "提示", "确定要移除设备吗？", () -> {
                            TuyaHomeSdk.newDeviceInstance(deviceId).removeDevice(new IResultCallback() {
                                @SuppressLint("NotifyDataSetChanged")
                                @Override
                                public void onSuccess() {
                                    ToastUtils.showShort("移除成功");
                                    deviceListAdapter.notifyDataSetChanged();
                                }

                                @Override
                                public void onError(String code, String error) {
                                    LogUtils.d(error);
                                }

                            });
                       });
                    return false;
                });

                List<BleConnectBuilder> builderList = new ArrayList<>();
                for (DeviceBean deviceBean : deviceBeans) {
                    TuyaHomeSdk.newDeviceInstance(deviceBean.devId).registerDevListener(iDevListener);
                    if (deviceBean.isBluetooth()) {
                        BleConnectBuilder builder = new BleConnectBuilder();
                        builder.setDevId(deviceBean.devId);
                        builderList.add(builder);
                    }
                }
                if (builderList.size() > 0) {
                    TuyaHomeSdk.getBleManager().connectBleDevice(builderList);
                }


            } else {
                getBinding().layoutEmpty.line1.setVisibility(View.VISIBLE);
            }
        });
    }
}
